<!--
*@Author: QWP
*@Description: 字典管理
*@Date: 2023-08-21 10:06:22
-->
<template>
  <a-layout class="f-h-100">
    <el-aside class="s-bg-white">
      <a-layout class="f-h-100">
        <a-layout-header style="height: auto; padding: 7px 12px 0">
          <a-form :model="baseForm">
            <a-row>
              <a-form-item label="年度" label-width="40px" class="f-fl">
                <u-date-picker v-model="baseForm['dicyear'+ dicType]" 
                  style="width: 100px"
                  type="year"
                  format="yyyy"
                  valueFormat="yyyy" 
                  placeholder="年度"
                  :allowClear="false"
                  @change="getTreedata('year')"/>
              </a-form-item>
              <a-form-item label="" label-width="12px" class="f-fl">
                <u-ptype-button itype="add" @click="copyNextYear">结转到下一年</u-ptype-button>
              </a-form-item>
            </a-row>
          </a-form>
        </a-layout-header>
        <a-layout-content style="padding: 0 6px 12px">
          <u-tree :data="treeData" v-if="refresh"
            ref="tree"
            :default-expanded-keys="treeExpandes"
            :expand-on-click-node="false"
            v-loading="loading"
            @node-click="treeNodeClick"/>
        </a-layout-content>
      </a-layout>
    </el-aside>
    <a-layout-content class="s-bg-white" style="margin-left: 12px; padding: 12px">
      <a-layout>
        <a-layout-header class="f-h-auto f-table-tool " style="padding: 0 0 12px">
          <u-ptype-button itype="save" @click="submit">保存</u-ptype-button>
          <u-ptype-button itype="delete" @click="deleteBtn">删除</u-ptype-button>
          <u-ptype-button itype="add" @click="addBtn">新增子级</u-ptype-button>
        </a-layout-header>
        <a-layout-content style="padding: 0; overflow: hidden">
          <u-form :elements="elements"  v-if="refresh"
            :model="form" 
            ref="form"
            v-bind="$attrs" />
        </a-layout-content>
      </a-layout>
    </a-layout-content>
  </a-layout>
</template>
<script>
import { isSel } from '@/common/model/base.js'
// import directoryService from '@/service/system/directory.service'
// import { createNamespacedHelpers } from 'vuex'
// const { mapGetters } = createNamespacedHelpers('routeStore')
export default {
  data () {
    return {
      refresh: true,
      baseForm: {
        dictype: ''
      },
      dicType: '',

      loading: false,
      currentCache: {},
      treeCurrentData: {},
      treeData: [],
      treeExpandes: [],

      form: {
        dictype: '',
        fkparentid: '',
        name: '',
        code: '',
        isuse: '1',
        isselect: '1',
        remark: '',
        keyid: ''
      },
      keyid: '',
      elements: [
        {element: 'cascader', label: '父级', span: 24, key: 'fkparentid', required: true , disabled: false,
          data: [], props: { checkStrictly: true }
        },
        {element: 'input', label: '名称', span: 24, key: 'name', required: true,
          "show-word-limit": true, "maxlength": 50,
        },
        {element: 'input', label: '代码', span: 12, key: 'code', required: true,
          "show-word-limit": true, "maxlength": 50,
          rules: [
            { pattern: /^\d+$/g, message: "功能模块代码只能输数字!", trigger: 'blur' }
          ]
        },
        {element: 'select', label: '是否启用', span: 12, key: 'isuse', required: true,
          data: isSel()
        },
        {element: 'select', label: '是否可选择', span: 12, key: 'isselect', required: true,
          data: isSel()
        },
        {element: 'input', label: '备注', type: 'textarea', span: 24, key: 'remark',
          "show-word-limit": true, "maxlength": 200,
        },
      ],
    }
  },
  computed: {
    getCurrentKey() {
      return this.$common.nullC(this.treeCurrentData['id'])
    },
    // ...mapGetters(['getParams'])
  },
  activated() {
    // this.dicType = this.getParams['dicType'];
    this.dicType = 1;
    this.pageChangeInit();
  },
  mounted() {
  },
  methods: {

    // 获取树形数据
    // type == init 为初次进入时的加载
    getTreedata(type) {
      if(type == 'year') {
        this.treeCurrentData = {};
      }
      const tbform = JSON.parse(JSON.stringify(this.baseForm));
      let fform = {
        dictype: tbform['dictype'],
        dicyear: tbform['dicyear' + this.$common.nullC(this.dicType)]
      };
      if(!fform['dictype']) {
        return
      }
      this.loading = true;
      return directoryService.tree(fform).then(res => {
        this.loading = false;
        if(res.data.code == 0) {
          this.treeData.splice(0, this.treeData.length, ...res.data.data)
          this.elements.splice(0, 1, { ...this.elements[0], data: res.data.data})
          if(this.treeData.length != 0 && type == 'init') {
            this.$refs.form.$refs.form.resetFields();
            this.treeExpandes.splice(0, this.treeExpandes.length, this.$common.nullC(this.treeData[0]['keyid']))
          }
        }
      })
      .catch(() => this.loading = false)
    },

    // 树形点击事件
    treeNodeClick(data) {
      if(data['keyid'] == 1 ) {
        this.$refs.form.$refs.form.resetFields();
      }
      this.treeCurrentData = data; 
      this.$set(this.form, 'keyid', data['keyid'])
      this.$set(this.currentCache, this.dicType, data)
      
      directoryService.singleQuery(data['keyid']).then(res => {
        this.elements.splice(0, 1, 
          { ...this.elements[0], 
            data: this.disableTreeKeyid(JSON.parse(JSON.stringify(this.treeData)), data['keyid'])
          }
        )
        
        this.clearValidate();
        if(res.data.code == 0) {
          for(let key in this.form) {
            if(this.$common.isValue(res.data.data[key])) {
              this.$set(this.form, key, res.data.data[key])
            }
          }
          this.form.isuse = this.$common.nullC(this.form.isuse) + '';
          this.form.isselect = this.$common.nullC(this.form.isselect) + '';
        }
        this.clearValidate();
       
        
      })
      .catch(() => {})
    },

    // 保存
    submit() {
      if(this.form['keyid'] == 1) {
        this.$common.alertC("顶级节点不能修改!");
        return
      }

      if(!this.treeCurrentData['keyid']) {
        this.$common.alertC("请先在左侧选择节点!");
        return
      }

      this.$refs.form.$refs.form.validate((vali) => {
        if(!vali) {
          this.$common.alertC("请先将必填字段填写完毕!");
          return
        } 

        const url = this.form.keyid ? 'update' : 'add';
        this.form.dicyear = this.baseForm['dicyear' + this.$common.nullC(this.dicType)];

        directoryService[url](this.form).then(async res => {
          if(res.data.code == '0') {
            this.$common.alertC(res.data.msg, "success");
            if(res.data.data) {
              for(let key in this.form) {
                if(this.$common.isValue(res.data.data[key])) {
                  this.$set(this.form, key, res.data.data[key])
                }
              }
              this.treeCurrentData = res.data.data;
            }
            
            this.form.isuse = this.$common.nullC(this.form.isuse) + '';
            this.form.isselect = this.$common.nullC(this.form.isselect) + '';
            
            await this.getTreedata();
            setTimeout(() => {
              this.treeExpandes.splice(0, this.treeExpandes.length, this.form.fkparentid+'')
              this.$refs.tree.$refs.tree.setCurrentKey(this.form.keyid);
            }, 20)
          }
          else {
            this.$common.alertC(res.data.msg, "warning");
          }
        })
        .catch(() => {})
      })
    },

    // 删除
    deleteBtn() {
      if(!this.$common.isValue(this.treeCurrentData['keyid'])) {
        this.$common.alertC("请选择要删除的节点!");
        return
      }
      
      if(this.treeCurrentData['keyid'] == this.treeData[0]['keyid'] && this.treeData.length == 1) {
        this.$common.alertC("不能删除顶级节点!");
        return
      }

      // 确认删除
      this.$common.confirmC({
        msg: "确认删除选中节点？", 
        title: '删除数据'
      }).then(() => {

        this.clearValidate();
        directoryService.delete({ids: this.treeCurrentData['keyid']}).then(async res => {
          if(res.data.code == 0) {
            await this.getTreedata();
            this.$common.alertC(res.data.msg, "success");
            this.$refs.form.$refs.form.resetFields();
            this.treeExpandes.splice(0, this.treeExpandes.length, this.treeCurrentData['fkparentid'] )
            this.treeCurrentData = {};
            this.form.keyid = '';
            this.form.fkparentid = '';
          }
          else {
            this.$common.alertC(res.data.msg, 'warning');
          }
        })
        .catch(() => {})

      })
      .catch(() => {})
    },

    // 新增子级
    addBtn() {
      if(!this.$common.isValue(this.treeCurrentData['keyid'])) {
        this.$common.alertC("请先在左侧选择节点!");
        return
      }
      
      this.$refs.form.$refs.form.resetFields();
      this.$set(this.form, 'fkparentid', this.treeCurrentData['keyid'])
      this.$set(this.form, 'isuse', '1')
      this.$set(this.form, 'dictype', this.dicType)
      this.$set(this.form, 'isselect', '1')
      this.$set(this.form, 'keyid', '')

      let index = this.elements.findIndex(item => item.key == 'fkparentid');
      this.elements.splice(index, 1, { ...this.elements[index], disabled: true })

      this.clearValidate();

    },

    // 结转到下一年
    copyNextYear() {
      let form = {
        dictype: this.baseForm.dictype,
        dicyear: this.baseForm['dicyear' + this.$common.nullC(this.dicType)],
        fkunitsid: ''
      }
      this.clearValidate();
      this.$common.confirmC({msg: '确认结转到下一年?'}).then(() => {

        directoryService.carryOver(form).then(res => {
          if(res.data.code == 0) {
            this.$common.alertC(res.data.msg, "success");
            this.getTreedata()
          }
          else {
            this.$common.alertC(res.data.msg, 'warning');
          }
        })
        .catch(() => {})
        
      })
      .catch(() => {})
    },

    // 初始化当前页面你的参数
    async pageChangeInit(nval, oval) {
      if(this.$refs['form']) {
        this.$refs.form.$refs.form.resetFields();
      }

      // 根据字典类型设置字典年度数据
      let yearKey = 'dicyear' + this.$common.nullC(this.dicType)
      if(!this.baseForm[yearKey]) {
        this.$set(this.baseForm, yearKey, new Date().getFullYear().toString())
      }

      // 获取当前页面的字典类型
      this.form.dictype = this.$common.nullC(this.dicType);
      this.baseForm.dictype = this.$common.nullC(this.dicType);
      // 获取字典类型的树形数据
      await this.getTreedata(this.currentCache[this.dicType] ? '' : 'init');

      if(this.currentCache[this.dicType]) {
        // 设置默认选中的数据
        this.treeCurrentData = this.currentCache[this.dicType]
        this.$refs.tree.$refs.tree.setCurrentKey(this.treeCurrentData['keyid'])

        // 默认展开的数据
        let fkparentid = this.treeCurrentData['fkparentid'] == 0 ? '1' : this.treeCurrentData['fkparentid'];
        this.treeExpandes.splice(0, this.treeExpandes.length, fkparentid)

        // 获取默认选中数据的详情
        this.treeNodeClick(this.treeCurrentData)
      }
      else {
        if(this.$refs.tree) this.$refs.tree.$refs.tree.setCurrentKey(null)
      }
    },

    // 清除已有的表单验证结果
    clearValidate() {
      setTimeout(() => this.$refs.form.$refs.form.clearValidate(), 50)
    },

    // 禁用当前选中的数据
    disableTreeKeyid(data, value) {
      let finData = JSON.parse(JSON.stringify(data))
      const dis = (tdata) => {
        tdata.forEach(item => {
          if(item.keyid == value) {
            item.disabled = true;
          }
          else if(item.children) {
            dis(item.children)
          }
        })
      } 
      dis(finData)

      return finData;
    }
  },
  watch: {
    // getParams: {
    //   handler: function(nval, oval) {
    //     if(nval['dicType'] && nval.name == "Dictionary") {
    //       this.dicType = nval['dicType'];
    //       this.pageChangeInit(nval, oval);
    //     }
    //   },
    //   immediate: true
    // },
    'form.keyid'(nval) {
      if(this.$common.isValue(nval)) {
        let index = this.elements.findIndex(item => item.key == 'fkparentid');
        this.elements.splice(index, 1, { ...this.elements[index], disabled: false  })
      }
    },
  }
}
</script>
<style lang='scss'>
</style>